package com.tfkj.contrller;

import com.tfkj.entity.QuestionType;
import com.tfkj.vo.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeBuilder {

    public static TreeNode buildTree(List<QuestionType> questionTypes) {
        Map<String, TreeNode> gradeNodes = new HashMap<>();
        Map<String, TreeNode> subjectNodes = new HashMap<>();

        for (QuestionType qt : questionTypes) {
            String grade = qt.getGrade();
            String subject = qt.getSubject();
            String questionType = qt.getQuestionType();
            Integer id = qt.getId();

            // Create or retrieve grade node
            TreeNode gradeNode = gradeNodes.computeIfAbsent(grade, k -> new TreeNode(grade));

            // Create or retrieve subject node, associate it with the grade
            String gradeSubjectKey = grade + ":" + subject;
            TreeNode subjectNode = subjectNodes.computeIfAbsent(gradeSubjectKey, k -> {
                TreeNode node = new TreeNode(subject);
                gradeNode.addChild(node);
                return node;
            });

            // Create leaf node for questionType and id
            TreeNode leafNode = new TreeNode(questionType);
            leafNode.setFullName(qt.getGrade() + "-" + qt.getSubject() + "-" + qt.getQuestionType());
            leafNode.setId(id.toString());
            String ids = subjectNode.getId();
            if (ids != null && !ids.isEmpty()) {
                ids = ids + "," + id;
            } else {
                ids = id.toString();
            }
            subjectNode.setFullName(qt.getGrade() + "-" + qt.getSubject());
            // Add leaf node to subject node
            subjectNode.addChild(leafNode);
            subjectNode.setId(ids);
        }

        // Create root node and add all grade nodes to it
        TreeNode rootNode = new TreeNode("root");
        for (TreeNode gradeNode : gradeNodes.values()) {
            rootNode.addChild(gradeNode);
        }

        return rootNode;
    }

}